//
//  AminoPrograming.m
//  AminoPrograming
//
//  Created by xiute on 2018/10/25.
//  Copyright © 2018 cuijin. All rights reserved.
//

#import "AminoPrograming.h"

@implementation AminoPrograming

+ (long)convertIpAddress:(NSString *)ipAddress {
    if (![ipAddress isKindOfClass:[NSString class]]) {
        @throw [[NSException alloc]initWithName:@"error" reason:@"入参不是字符串，差评" userInfo:nil];
    }
    NSArray<NSNumber *> *ipNumbers = nil;
    @try {
        ipNumbers = [self validateIpAddress:ipAddress];
    } @catch (NSException *exception) {
        @throw exception;
        return 0;
    } @finally {
        
    }
    __block long finalValue = 0;
    
    [ipNumbers enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        int bitValue = (3 - (int)idx) * 8;
        finalValue += obj.integerValue << bitValue;
    }];
    
    return finalValue;
}

/**
 判断是否是否是合法的ip

 @return YES即为合法
 */
+ (NSArray<NSNumber *> *)validateIpAddress:(NSString *)ipAddress {
    NSArray<NSString *> *ipNumbers = [ipAddress componentsSeparatedByString:@"."];
    if (ipNumbers.count != 4) {
        @throw [[NSException alloc]initWithName:@"error" reason:@"没有仨点，差评" userInfo:nil];
        return nil;
    }
    
    NSMutableArray<NSNumber *> *ipArray = [NSMutableArray array];
    for (NSString *ipNumber in ipNumbers) {
        NSString *handledIPNumber = [ipNumber stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (handledIPNumber.length == 0) {
            @throw [[NSException alloc]initWithName:@"error" reason:@"什么鬼字符串，差评" userInfo:nil];
            break;
        }
        
        NSString *regex = @"[0-9]*";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        if (![pred evaluateWithObject:handledIPNumber]) {
            @throw [[NSException alloc]initWithName:@"error" reason:@"每一个地址位不是纯数字，差评" userInfo:nil];
            break;
        }
        
        [ipArray addObject:@(handledIPNumber.integerValue)];
        
        
    }
    return ipArray;
}

@end
